package com.maolvche.controller;

import com.maolvche.pojo.*;
import com.maolvche.service.LoginService;
import com.maolvche.service.UserInfoService;
import com.maolvche.util.RandomStringUtil;
import com.maolvche.util.getUserIp;
import com.maolvche.vo.WebUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author HackerAC
 */
@Controller
public class LoginController {
    @Resource
    LoginService loginService;

    @Resource
    UserInfoService userInfoService;


    /**登录
     * 网站登录业务
     */
    @RequestMapping(value="/loginToWeb")
    public ModelAndView login(HttpServletRequest request,HttpSession session, ModelAndView modelAndView, @RequestParam("loginText") String userAcc, @RequestParam("pwd") String password){
        //网站用户视图对象
        WebUser webUser=new WebUser();
        UserInfo userInfo;
        WebAccount webAccount;
        //空值处理
        if(userAcc==null||"".equals(userAcc)||password==null||"".equals(password)){
            modelAndView.setViewName("login");
            modelAndView.addObject("errInfo","输入的登录信息不能为空！");
        }else{
            try{
                //优先根据用户名和密码查询
                //获取用户账户信息
                webAccount=loginService.selByUsernameAndPwd(userAcc,password);
                modelAndView.addObject("thisNav",1);
                modelAndView.setViewName("index");
                //获取用户基本信息
                userInfo=userInfoService.selByUserNo(webAccount.getUserno());

                //获取IP地址
                String ip = getUserIp.getIpAddr(request);
                //构建登录日志
                LoginRecord loginRecord=new LoginRecord();
                loginRecord.setUseracc(webAccount.getUseracc());
                loginRecord.setLoginip(ip);
                loginRecord.setLogintime(new Date());
                //添加登录日志
                loginService.insertLoginRecord(loginRecord);

                //封装已登录用户信息到视图对象WebUser中。
                webUser.setAccountInfo(webAccount);
                webUser.setUserInfo(userInfo);
                //将用户信息保存在session中
                session.setAttribute("LOGIN_USER",webUser);
                session.setAttribute("info","200");
            }catch (Exception e){
                try {
                    //其次根据手机号和密码查询
                    //获取对应手机号的用户编号
                    String userNo = userInfoService.selByUserPhone(userAcc).getUserno();
                    //转换为用户编号和密码查询
                    webAccount=loginService.selByUserNoAndPwd(userNo,password);
                    userInfo=userInfoService.selByUserNo(userNo);

                    //获取IP地址
                    String ip = getUserIp.getIpAddr(request);
                    //构建登录日志
                    LoginRecord loginRecord=new LoginRecord();
                    loginRecord.setUseracc(webAccount.getUseracc());
                    loginRecord.setLoginip(ip);
                    loginRecord.setLogintime(new Date());
                    //添加登录日志
                    loginService.insertLoginRecord(loginRecord);

                    modelAndView.addObject("thisNav",1);
                    modelAndView.setViewName("index");
                    modelAndView.addObject("info","200");
                    //封装已登录用户信息到视图对象WebUser中。
                    webUser.setAccountInfo(webAccount);
                    webUser.setUserInfo(userInfo);
                    //将成功登陆后的用户信息保存在session中
                    session.setAttribute("LOGIN_USER",webUser);
                    session.setAttribute("info","200");
                }catch (Exception exc) {
                    modelAndView.setViewName("login");
                    modelAndView.addObject("errInfo","输入的登录信息有误！");
                    session.setAttribute("info","");
                }
            }
        }
        return modelAndView;
    }

    /**注销
     * 网站登录注销业务
     */
    @RequestMapping(value="/SignOut")
    public ModelAndView cleanLoginInfo(HttpSession session,ModelAndView modelAndView) {
        session.removeAttribute("LOGIN_USER");
        modelAndView.addObject("thisNav",1);
        modelAndView.setViewName("login");
        session.setAttribute("info","");
        return modelAndView;
    }

    /**登录
     * 后台管理登录业务——管理员
     */
    @RequestMapping(value="/admlogin")
    public ModelAndView toBgAdmIndex(HttpSession session,ModelAndView modelAndView, @RequestParam("admAcc") String adminAcc, @RequestParam("admPwd") String adminPwd){
        try{
            BgAccount bgAccount=loginService.selAdminByUsernameAndPwd(adminAcc,adminPwd);
            //将登录的管理员信息存放到session中
            session.setAttribute("BGMS_ADMIN",bgAccount);
            modelAndView.setViewName("BGMSAdminIndex");
        }catch (Exception e){
            modelAndView.addObject("errInfo","用户名或密码错误！");
            modelAndView.setViewName("BGMSLoginAdm");
        }
        return modelAndView;
    }

    /**注销
     * 后台管理注销登录业务——管理员
     */
    @RequestMapping(value="/logoutadm")
    public ModelAndView cleanAdmLogin(ModelAndView modelAndView,HttpSession session){
        if(session.getAttribute("BGMS_ADMIN")!=null){
            session.removeAttribute("BGMS_ADMIN");
        }
        modelAndView.setViewName("BGMSLoginAdm");
        return modelAndView;
    }

    /**登录控制器
     * 后台管理登录业务——员工
     */
    @RequestMapping(value="/emplogin")
    public ModelAndView toBgEmpIndex(HttpSession session,ModelAndView modelAndView, @RequestParam("employAcc") String employAcc, @RequestParam("employPwd") String employPwd){
        try{
            EmpAccount empAccount=loginService.selEmployByUsernameAndPwd(employAcc,employPwd);
            //将登录的员工账户信息存入session
            session.setAttribute("BGMS_EMPLOY",empAccount);
            modelAndView.setViewName("BGMSempIndex");
        }catch (Exception e){
            modelAndView.addObject("errInfo","用户名或密码错误！");
            modelAndView.setViewName("BGMSLoginEmp");
        }
        return modelAndView;
    }

    /**注销
     * 后台管理注销登录业务——员工
     */
    @RequestMapping(value="/logoutemp")
    public ModelAndView cleanEmpLogin(HttpSession session,ModelAndView modelAndView){
        if(session.getAttribute("BGMS_EMPLOY")!=null){
            session.removeAttribute("BGMS_EMPLOY");
        }
        modelAndView.setViewName("BGMSLoginEmp");
        return modelAndView;
    }

    /**
     * 网站用户登录日志查询
     */
    @RequestMapping(value = "/loginRecord")
    @ResponseBody
    public List<LoginRecord> getLoginRecord(HttpSession session) {
        WebUser webUser=(WebUser)session.getAttribute("LOGIN_USER");
        return loginService.selLoginRecordByUserAcc(webUser.getAccountInfo().getUseracc());
    }

    /**
     * 删除登录日志
     * @param recordNo 登录日志编号
     */
    @RequestMapping(value = "/delLoginRecord")
    @ResponseBody
    public String delLoginRecord(@RequestParam("recordNo") String recordNo){
        loginService.delLoginRecord(recordNo);
        return "ok";
    }

    /**
     * 修改密码
     * @param originPwd 原密码
     * @param newPwd 新密码
     */
    @RequestMapping(value = "/modifyPwd")
    @ResponseBody
    public int uptUserPwd(HttpSession session,@RequestParam("originPwd") String originPwd, @RequestParam("newPwd") String newPwd){
        WebUser webUser=(WebUser)session.getAttribute("LOGIN_USER");
        if(!webUser.getAccountInfo().getUserpwd().equals(originPwd)){
            return 2;
        }else{
            WebAccount webAccount = webUser.getAccountInfo();
            webAccount.setUserpwd(newPwd);
            return loginService.uptPwdByAccAndNewPwd(webAccount);
        }
    }

    /**
     * 修改账户信息(账号，手机号，邮箱，昵称，地址)
     */
    @RequestMapping(value = "/modifyPersonInfo")
    @ResponseBody
    public String uptUserPersonInfo(HttpSession session,@RequestParam("newUsername") String newUsername,@RequestParam("newPhone") String newPhone, @RequestParam("newEmail") String newEmail,@RequestParam("newNickName") String newNickName,@RequestParam("newAddress") String newAddress){
        WebUser webUser=(WebUser)session.getAttribute("LOGIN_USER");
        //读取当前用户的个人信息
        UserInfo userInfo = webUser.getUserInfo();
        WebAccount webAccount = webUser.getAccountInfo();
        //由于用户名是用来进行登录的，所以修改之前必须判断其是否已经被其他用户使用。
        //即新用户名和当前用户的用户名不同，但是数据库中又存在一条数据说明，该用户名是被其他用户使用
        if(!webAccount.getUsername().equals(newUsername) && loginService.getWebAccountByUsername(newUsername)!=null){
            return "BUN";
        }else if(!userInfo.getPhone().equals(newPhone) && userInfoService.selByUserPhone(newPhone)!=null){
            //接下来同样需要判断用于登录的手机号是否已经被使用。
            return "BP";
        }else{

        //更新用户信息
        userInfo.setAddress(newAddress);
        userInfo.setPhone(newPhone);
        userInfo.setUseremail(newEmail);
        webAccount.setNickname(newNickName);
        webAccount.setUsername(newUsername);

        //执行数据库操作
        try{
            loginService.uptUserInfo(userInfo);
            loginService.uptUserAccInfo(webAccount);
            return "ok";
        }catch (Exception e){
            return "Er";
        }
        }
    }

    /**
     * 注册
     * @param phone
     * @param pwd
     * @param nickname
     * @return
     */
    @RequestMapping(value = "/signup")
    @ResponseBody
    public int signToBeWebUser(@RequestParam("phone")String phone,@RequestParam("pwd")String pwd,@RequestParam("nickname")String nickname){
        //查询是否存在相同手机号的用户
        if(userInfoService.selByUserPhone(phone)!=null){
            return 1;
        }else{
            //为新用户创建账号
            UserInfo userInfo = new UserInfo();
            WebAccount webAccount = new WebAccount();
            int ifsign;
            int times = 0;
            do {
                //默认初始化信息
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String beforeNo = (sdf.format(new Date())).substring(2, 8);
                Long longs = (new Date()).getTime();
                String backNo = (longs.toString()).substring(7);
                String userAcc = beforeNo + backNo;

                userInfo.setPhone(phone);
                userInfo.setUserno(userAcc);
                webAccount.setUseracc(userAcc);
                //通过工具类随机设置用户名
                webAccount.setUsername(RandomStringUtil.getStringRandom(12));
                webAccount.setNickname(nickname);
                webAccount.setUserpwd(pwd);
                webAccount.setRegisterdate(new Date());
                webAccount.setUserno(userAcc);

                int a=userInfoService.addUserInfo(userInfo);
                int b=loginService.addUserAccInfo(webAccount);
                ifsign = a+b;
                if(a==1&&b==0){
                    userInfoService.delUserInfo(userInfo);
                }else if(a==0&&b==1){
                    loginService.delUserAccInfo(webAccount);
                }
                times++;
            }while (ifsign<=1&&times<4);

            return ifsign;
        }

    }

}
